import {
  createRouter,
  createWebHistory
} from "vue-router";

import asyncRoutes from "./async-routes";

import {
  getToken
} from "@/utils/storage";
import store from "@/store";

const routes = [
  {
    path: "/login",
    name: "Login",
    meta: {
      title: "注册登录",
    },
    component: () =>
      import(/* webpackChunkName: "login" */ "@/views/components/login/index"),
  },
];

const router = createRouter({
  history: createWebHistory("/"),
  routes,
});

const givenPath = ["/login", "/404", "/error"];

// if (getToken()) {
//   if (!givenPath.includes(location.pathname.split("/")[1])) {
//     store.dispatch("user/GetUserInfo");
//   }
// }
//路由前置守卫
router.beforeEach((to, from, next) => {
  // next();
  // document.title = to.meta.title || "农爱问管理平台"
  if (givenPath.includes(to.query)) {
    console.log("!11")
    next()
  } else if (getToken()) {
    console.log(store.state.isRouter);
    if (!store.state.isRouter) {
      next({
        path: to.path,
        query: {
          ...to.query
        }
      });
      asyncRoutes.general.map((item) => {
        router.addRoute(item);
      });
      store.commit("commitSave", {
        key: "isRouter",
        data: true,
      });
      // 重载路由
      next({
        path: to.path,
        query: {
          ...to.query
        }
      });
    } else {
      next();
    }
  } else {
    if (givenPath.includes(to.path)) {
      next();
    } else {
      next({
        path: "/login",
        query: {
          ...to.query
        }
      });
    }
  }
});
export default router;
